# coding=utf-8
from django.db import transaction
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from com.kjssoft.common.ant.sercurity.sha256 import SHA256
from com.kjssoft.common.globals import EagleyeAssist
from com.kjssoft.eagleye import LOGGER
from com.kjssoft.eagleye.forms import UserAuthorizeForm, RegisterForm
from com.kjssoft.eagleye.models import EEUser
from com.kjssoft.eagleye.social.consts import EagleyeSocialConsts
from com.kjssoft.eagleye.social.forms import EagleyeBindForm
from com.kjssoft.eagleye.social.models import Bind, Auth
from com.kjssoft.eagleye.social.platform import SocialBindClientServiceException, PlatformBindConsts
from django.contrib.auth import login as auth_login, login, logout
from com.kjssoft.eagleye.views import login_when_registered
from settings.settings import SECRET_KEY

__author__ = 'KJS'

def social_authorize_view_page(request, bind):
    try:
        bind = Bind.objects.get(id = int(bind))
        print(bind)
        social_client_server_model = 'com.kjssoft.eagleye.social.platform.%s' % bind.platform.name.strip().lower()
        models = social_client_server_model.split('.')
        model = __import__(social_client_server_model)
        for m in models[1:]:
            model = getattr(model, m)
        platform_client_model = getattr(model, 'BindClientServer')
        platform_client_model = platform_client_model(bind)
        social_auth_url = platform_client_model.get_social_auth_url(request.get_host())
        return redirect(social_auth_url)
    except Bind.DoesNotExist as e:
        raise SocialBindClientServiceException(
            PlatformBindConsts.ErrorCode.INVALID_BIND_INFORMATION,
            'INVALID_BIND_INFORMATION %s' % e
        )

def connect_view_page(request):
    bind = None
    try:
        bind_id = request.GET.get('bind')
        bind = Bind.objects.get(id = bind_id)
        social_client_server_model = 'com.kjssoft.eagleye.social.platform.%s' % bind.platform.name.strip().lower()
        models = social_client_server_model.split('.')
        model = __import__(social_client_server_model)
        for m in models[1:]:
            model = getattr(model, m)
        platform_client_model = getattr(model, 'BindClientServer')
        code = request.GET.get('code')
        platform_client_model = platform_client_model(bind, code)

        social_auth = platform_client_model.get_social_user_auth(request.get_host())
        if social_auth.social_user.bind_user:
            #该平台号已经绑定一个账号，完成登录过程
            auth_login(request, social_auth.social_user.bind_user)
            #登录成功跳转到应用页面
            return redirect('http://%s/%s/welcome/' % (request.get_host(), social_auth.bind.application.name.lower()))
        else:
            #用户未绑定，跳转到咨询绑定页面
            LOGGER.debug('===========================================')
            auth_id = SHA256().sha256_encode(str(social_auth.id), '%s_%s' % (
                social_auth.access_token,
                SECRET_KEY
            ))
            bind_url = 'http://%s%s' % (request.get_host(), EagleyeAssist.get_bind_url(social_auth = auth_id))
            LOGGER.debug('bind url %s' % bind_url)
            return redirect(bind_url)
    except Bind.DoesNotExist as e:
        return redirect(
            'http://%s%s' % (
                request.get_host(),
                EagleyeAssist.get_login_url()
            )
        )
    except Exception as e:
        LOGGER.error(e, 'out of time')
        return redirect('http://%s%s%s' % (
            request.get_host(),
            EagleyeAssist.get_login_url(),
            '?app=%s' % bind.application.name
        ))

def social_auth_bind_wrapper(view_func):
    def _wrapper_view_func(request):
        social_auth_id = request.GET.get('social_auth')
        request.social_auth = None
        login_url = 'http://%s%s' % (request.get_host(), EagleyeAssist.get_login_url())
        if social_auth_id:
            try:
                LOGGER.debug('social auth id %s' % social_auth_id)
                a_social_auth_id = SHA256().sha256_decode(social_auth_id, security=False)
                LOGGER.debug('social auth id %s' % a_social_auth_id)
                social_auth = Auth.objects.get(id = a_social_auth_id)
                tmp_social_auth_id = SHA256.sha256_encode(str(social_auth.id), '%s_%s' % (
                    social_auth.access_token,
                    SECRET_KEY
                ))
                LOGGER.debug('social auth id %s' % tmp_social_auth_id)
                if social_auth_id == tmp_social_auth_id:
                    if social_auth.social_user.bind_user:
                        logout(request)
                        login(request, social_auth.social_user.bind_user)
                        return redirect('http://%s/%s/welcome/' % (
                            request.get_host(), social_auth.bind.application.name.lower()
                        ))
                    request.social_auth = social_auth
                    LOGGER.debug(view_func)
                    return view_func(request)
            except Auth.DoesNotExist:
                return redirect(login_url)
            except Exception as e:
                LOGGER.error('error exception %s' % e)
                return redirect(login_url)
        return redirect(login_url)
    return _wrapper_view_func

def _bind(eeuser, request):
    LOGGER.debug('%s bind with %s.' % (eeuser, request.social_auth.social_user))
    app_welcome_response = redirect('http://%s/%s/welcome/' % (
        request.get_host(), request.social_auth.bind.application.name.lower()
    ))
    social_user = request.social_auth.social_user
    social_user.bind_user = eeuser
    social_user.save()
    return app_welcome_response

@social_auth_bind_wrapper
@sensitive_post_parameters()
@csrf_protect
@never_cache
@transaction.commit_on_success
def bind_view_page(request):
    """
    社交平台账号与惠软账号绑定
    """
    LOGGER.debug('=========================== bind view page ===========================')
    default_bind_type = EagleyeSocialConsts.Bind.BIND_TYPE_LOGIN_USER
    current_bind_type = None
    if not request.user or not request.user.is_authenticated():
        default_bind_type = EagleyeSocialConsts.Bind.BIND_TYPE_RE_LOGIN_USER
    bind_form     = EagleyeBindForm(initial= {
        'bind_type':default_bind_type
    }, user=None)
    login_form    = UserAuthorizeForm(request)
    register_form = RegisterForm(initial= {})
    LOGGER.debug('bind view page initial form')
    if request.POST:
        LOGGER.debug('has parameters submit from client')
        bind_form = EagleyeBindForm(request.POST, request.user)
        if bind_form.is_bound and bind_form.is_valid():
            bind_type = bind_form.cleaned_data.get('bind_type')
            bind_type = int(bind_type)
            LOGGER.debug('bind type %s' % bind_type)
            current_bind_type = bind_type
            #与登陆用户绑定
            if EagleyeSocialConsts.Bind.BIND_TYPE_LOGIN_USER == bind_type:
                LOGGER.debug('%s bind with %s' % (request.user, request.social_auth.social_user))
                return _bind(request.user, request)
            elif EagleyeSocialConsts.Bind.BIND_TYPE_RE_LOGIN_USER == bind_type:
                login_form = UserAuthorizeForm(data = request.POST)
                if login_form.is_bound and login_form.is_valid():
                    user = login_form.get_user()
                    login(request, user)
                    user = EEUser.objects.get(id = user.id)
                    return _bind(user, request)
            elif EagleyeSocialConsts.Bind.BIND_TYPE_NEW_REGISTER_USER == bind_type:
                register_form = RegisterForm(request.POST)
                if register_form.is_bound and register_form.is_valid():
                    register_form.save()
                    #注册成功跳转到用户信息界面
                    user = register_form.instance
                    #用户分组, project KjsSoft所有用户都是属于组EEUser_Group
                    data = register_form.cleaned_data
                    nickname = data.get('nickname')
                    user.initial(nickname)
                    #注册用户成功，发送验证邮件给用户
                    login_when_registered(user.username, data.get('password1'), request)
                    return _bind(user, request)
            else:
                #绑定到随机用户
                user = EEUser.set_random_account(request.social_auth.social_user.name)
                login_when_registered(user.username, user.username, request)
                return _bind(user, request)
    LOGGER.debug('=========================== bind view page ===========================')
    return render_to_response(
        'kjs/eagleye/social/bind.html',
        {
            'social_auth_id'    : request.GET.get('social_auth'),
            'social_auth'       : request.social_auth,
            'default_bind_type' : default_bind_type,
            'current_bind_type' : current_bind_type,
            'bind_form'         : bind_form,
            'login_form'        : login_form,
            'register_form'     : register_form,
            'bind_consts'       : EagleyeSocialConsts.Bind
        },
        context_instance = RequestContext(request)
    )